<template>
  <div class="chat">
    <!-- 顶部信息操作栏 -->
    <div class="options drag">
      <span
        class="iconfont icon icon-gengduo1 no_drag"
        @click="optionHandle"
      ></span>
      <!-- 操作弹层 -->
      <div
        v-if="isLayer && info.msg === 'ok' && type === 'user'"
        class="option_layer"
      >
        <userOption
          :item="info"
          @edit-name="editName"
          @edit-look="editLook"
        ></userOption>
      </div>
      <div
        v-if="isLayer && info.msg === 'ok' && type === 'group'"
        class="option_layer"
      >
        <userOption :item="info"></userOption>
      </div>
    </div>
    <div class="chat_list" @click="closeLayer">
      <div class="chat_top">
        <div v-for="item in chatStore.messageList" :key="item.id">
          <RightChatItem
            v-if="userStore.userInfo.id == item.from_id"
            :item="item"
          ></RightChatItem>
          <LeftChatItem v-else :item="item"></LeftChatItem>
        </div>
      </div>
      <div class="chat_option">
        <ChatBar @sendMsg="sendMsg"></ChatBar>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { message } from '@renderer/utlis/feedback'

import userOption from './c-cnps/user-option.vue'
import LeftChatItem from './c-cnps/left-chat-item.vue'
import RightChatItem from './c-cnps/right-chat-item.vue'
import ChatBar from './c-cnps/chat-bar.vue'
import useFriend from '@renderer/pinai/modules/friend'
import useGroup from '@renderer/pinai/modules/group'
import useList from '@renderer/pinai/modules/list'
import useUser from '@renderer/pinai/modules/user'
import useChat from '@renderer/pinai/modules/chat'

const route = useRoute()
const friendStore = useFriend()
const listStore = useList()
const userStore = useUser()
const groupStore = useGroup()
const chatStore = useChat()

const info = ref<any>({}) // 当前页面的基本信息
const type = ref<string>('user') // 当前页面类型
const isLayer = ref(false) // 控制弹层是否显示
const f_id = ref<any>('') // 当前朋友的id
const f_t_id = ref<any>('') // friend表的id
const msgList = ref<any>([]) // 消息列表
const chatParams = reactive({
  type: '',
  id: '',
  friend_id: '',
  name: '',
  avatar: '',
  chat_type: '',
  data: ''
}) // 创建聊天对象所需要的参数

// 获得朋友信息
const getFriendInfo = (f_id, id) => {
  friendStore.getFriendInfoAction({ id: f_id, friend_id: id }).then((res) => {
    // 将数据扁平化
    const data = res.map((m) => m.data).reduce((a, b) => ({ ...a, ...b }))
    // 整理格式
    info.value = {
      nickname: data.bfriends[0].nickname,
      name: data.username,
      avatar: data.avatar,
      friend_id: data.bfriends[0].friend_id,
      id: data.bfriends[0].id,
      group_id: '',
      sex: data.sex,
      sign: data.sign,
      lookme: data.lookme ? true : false,
      lookhim: data.lookhim ? true : false,
      email: data.email,
      area: data.area,
      msg: 'ok',
      type: 'user'
    }
  })
}

// 监听路由的变化
watch(
  () => route.query,
  (newRoute) => {
    console.log(newRoute)
    type.value = newRoute.type as string
    f_id.value = newRoute.friend_id
    f_t_id.value = newRoute.id
    console.log(type.value, f_id.value, f_t_id.value)

    info.value = {}
    // 重新获取用户或者群聊的信息
    if (type.value === 'user') {
      getFriendInfo(f_id.value, f_t_id.value)
      chatParams.id = f_t_id.value
      chatParams.name = route.query.name as string
      chatParams.avatar = route.query.avatar as string
      chatParams.chat_type = 'user'
    }
    if (type.value === 'group') {
      groupStore.getGroupInfoAction(f_t_id.value).then((res) => {
        info.value = res
        info.value.type = 'group'
        info.value.msg = 'ok'
      })
      chatParams.id = f_t_id.value
      chatParams.name = route.query.g_name as string
      chatParams.avatar = route.query.avatar as string
      chatParams.chat_type = 'group'
    }
    // 获取消息列表
    getMsgList()
  }
)

onMounted(() => {
  type.value = route.query.type as string
  f_id.value = route.query.friend_id
  f_t_id.value = route.query.id
  info.value = {}
  if (type.value === 'user') {
    friendStore
    getFriendInfo(f_id.value, f_t_id.value)
    chatParams.id = f_t_id.value
    chatParams.name = route.query.name as string
    chatParams.avatar = route.query.avatar as string
    chatParams.chat_type = 'user'
  }
  if (type.value === 'group') {
    friendStore
    groupStore.getGroupInfoAction(f_t_id.value).then((res) => {
      info.value = res
      info.value.type = 'group'
      info.value.msg = 'ok'
    })
    chatParams.id = f_t_id.value
    chatParams.name = route.query.g_name as string
    chatParams.avatar = route.query.avatar as string
    chatParams.chat_type = 'group'
  }
  // 创建聊天对象
  setTimeout(() => {
    userStore.socket?.createChatObject(chatParams)
  })
  // 获取消息列表
  getMsgList()
})

// 获得当前的消息列表
const getMsgList = () => {
  const user_id = userStore.userInfo.id
  msgList.value = chatStore.getMessageList(user_id, f_t_id.value * 1)
}

// 点击发送消息
const sendMsg = (content: any) => {
  chatParams.type = content.type || 'text'
  chatParams.data = content
  chatParams.friend_id = route.query.friend_id as string
  console.log(chatParams)
  userStore.socket.sendMsg(userStore.socket.formatSendData(chatParams))
  // 重新获得消息列表
  chatStore.getMessageList(
    userStore.userInfo.id,
    f_t_id.value * 1,
    chatParams.chat_type
  )
}

// 点击操作好友或者群聊的按钮
const optionHandle = () => {
  console.log('optionHandle')
  isLayer.value = !isLayer.value
}
// 点击其他地方关闭弹层
const closeLayer = () => {
  isLayer.value = false
}

// 修改群名称或者好友备注
const editName = (val: any) => {
  if (val.type === 'user') {
    friendStore
      .editFriendNickname({
        nickname: val.name,
        id: val.id
      })
      .then(() => {
        message('修改成功')
        listStore.getFriendList()
        getFriendInfo(val.f_g_id, val.id)
      })
  }
  console.log(val)
}

// 修改是否看得到
const editLook = (val: any) => {
  console.log(val)
  friendStore
    .updateCirclePermissionAction(val.id, {
      lookme: val.lookme ? 1 : 0,
      lookhim: val.lookhim ? 1 : 0
    })
    .then(() => {
      message('修改成功', 'success')
      getFriendInfo(f_id.value, f_t_id.value)
    })
}
</script>

<style lang="scss" scoped>
.chat {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .options {
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 30px;
    position: relative;

    .option_layer {
      position: absolute;
      top: 30px;
      right: 15px;
      z-index: 999;
      border-radius: 5px;
      background: #fff;
      padding: 15px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .icon {
      font-size: 20px;
      color: #000;
      cursor: pointer;
    }
  }

  .chat_list {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    box-sizing: border-box;

    .chat_top {
      flex: 1;
      padding: 0 20px;
      overflow-y: scroll;
      /* background-color: blue; */
    }
    .chat_option {
      width: 100%;
      height: 140px;
      display: flex;
      flex-direction: column;
    }
  }
}
</style>
